package atm;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TransPanel extends JPanel implements ActionListener {
    private ATM atm;
    private JButton sureBtn;
    private JButton clearBtn;
    private Icon sureImg = Util.getImageIcon("/images/buttonSure.jpg");
    private Icon clearImg = Util.getImageIcon("/images/buttonOff.jpg");

    private JTextField zhuan1 = new JTextField();
    private JTextField zhuan2 = new JTextField();

    public JTextField getZhuan1() {
        return zhuan1;
    }

    public void setZhuan1(JTextField zhuan1) {
        this.zhuan1 = zhuan1;
    }

    public JTextField getZhuan2() {
        return zhuan2;
    }

    public void setZhuan2(JTextField zhuan2) {
        this.zhuan2 = zhuan2;
    }

    public TransPanel(ATM atm) {
        this.atm = atm;
        this.setLayout(null);
        this.setOpaque(false);

        sureBtn = new JButton(sureImg);
        sureBtn.setBounds(10, 40, 140, 50);
        this.add(sureBtn);
        sureBtn.addActionListener(this);

        clearBtn = new JButton(clearImg);
        clearBtn.setBounds(10, 100, 140, 50);
        this.add(clearBtn);
        clearBtn.addActionListener(this);

        JLabel changes1 = new JLabel("请输入转账人");
        changes1.setBounds(400, 220, 90, 20);
        this.add(changes1);

        zhuan1.setBounds(510, 220, 90, 20);
        this.add(zhuan1);

        JLabel changes2 = new JLabel("请输入转账金额");
        changes2.setBounds(400, 250, 90, 20);
        this.add(changes2);

        zhuan2.setBounds(510, 250, 90, 20);
        this.add(zhuan2);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sureBtn) {
//            System.out.println(zhuan1.getText());
//            System.out.println(atm.getUsers().get(atm.getA()).getName());
            for (int i = 0; i < atm.getUsers().size(); i++) {
                if (zhuan1.getText().equals(atm.getUsers().get(i).getName())) {
                    if (Double.valueOf(zhuan2.getText()) <= (atm.getUsers().get(i).getMoney())) {
                        JOptionPane.showMessageDialog(
                                this,
                                "转账成功，本次转账金额为：" + zhuan2.getText());
                        atm.getUsers().get(atm.getA()).setMoney(atm.getUsers().get(atm.getA()).getMoney()
                                -Double.valueOf(zhuan2.getText()));
                        atm.getUsers().get(i).setMoney(atm.getUsers().get(i).getMoney()
                                +Double.valueOf(zhuan2.getText()));

                        atm.switchPanel("login");
                        return;
                    }
                    JOptionPane.showMessageDialog(this, "转账失败，余额不足");
                    return;
                }


            }
            JOptionPane.showMessageDialog(this, "转账失败，用户名不对");
        } else if (e.getSource() == clearBtn) {
            atm.switchPanel("menu");
        }
    }
}